import os
import random

import httpx
from loguru import logger
from pydantic import BaseModel

REMOTE_DOMAIN = "https://www.rcisyn.net/athena-api-prod/api"

customer_headers = {
	"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0 (Immersed/44) uni-app",
}

auth_headers: dict[str, str] = {"Authorization": os.getenv("AUTH_TOKEN")}


class RemoteData(BaseModel):
	code: int
	msg: str


class SliderCodeResponse(RemoteData):
	data: int | None = None


class LoginRequest(BaseModel):
	account: str
	password: str
	sliderCode: int
	timestamp: float


class LoginResponse(RemoteData):
	data: dict[str, dict | bool | str] | None = None


class PunchClockRequest(BaseModel):
	lgt: float
	lat: float
	cardPlace: str
	cardType: int
	userFaceUrl: str


def slider_code(random_str: str) -> int:
	request_url = "{}/file/SliderCode/{}".format(REMOTE_DOMAIN, random_str)
	response = httpx.get(request_url, headers=customer_headers)
	logger.info(f"slider_code_response = {str(response.content, 'utf-8')}")
	model = SliderCodeResponse.model_validate_json(response.content)
	assert model.code == 200
	return model.data


def login(account: str, password: str):
	random_num = random.random()
	slider_code_data = slider_code(str(random_num))
	request_url = "{}/oauth/Login?client_id=admin&client_secret=123456&version=v2&scope=all&grant_type=password".format(REMOTE_DOMAIN)
	request = LoginRequest(account=account, password=password, sliderCode=slider_code_data, timestamp=random_num)
	response = httpx.post(request_url, headers=customer_headers, json=request.model_dump())
	logger.info(f"login response = {str(response.content, 'utf-8')}")
	model = LoginResponse.model_validate_json(response.content)
	assert model.code == 200
	token_str = str(model.data["token"])
	auth_headers["Authorization"] = token_str
	return token_str


def punch_clock(request: PunchClockRequest):
	request_url = "{}/attendance/mobile/attendance/staff/punchTheClock".format(REMOTE_DOMAIN)
	response = httpx.post(request_url, headers={**customer_headers, **auth_headers}, json=request.model_dump())
	response_data = str(response.content, "utf-8")
	logger.info(f"login response = {response_data}")
	return response_data


def get_user_statics(date_time):
	input_data = {"time": date_time}
	request_url = "{}/attendance/mobile/attendance/staff/getUserStatics".format(REMOTE_DOMAIN)
	response = httpx.post(request_url, json=input_data, headers={**customer_headers, **auth_headers})
	response_data = str(response.content, encoding="utf-8")
	logger.info(f"getUserStatics response = {response_data}")
	response.close()
	return response_data
